#include "framewindow.h"
#include "recognize_mcu_com.h"

#include <QSerialPortInfo>


#include <QDateTime>
#include <QDebug>

Recognize_MCU_COM::Recognize_MCU_COM()
{

}

Recognize_MCU_COM::Recognize_MCU_COM(FrameWindow *parent)
{
    comList.append("NEOWAY HS-USB TTY AT 3C93");// 有方
    comList.append("HUAWEI Mobile Connect - PC UI Interface");    // 思极

    this->parent = parent;
}


QString Recognize_MCU_COM::FindMCU_COM(){

    QString com_name;
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {

        if(!info.description().isEmpty()){

            // 设置串口号
            QSerialPort * serialPort = new QSerialPort();
            serialPort->setPortName(info.portName());

            /*
            if(serialPort->isOpen())//如果串口已经打开了 先给他关闭了
            {
                serialPort->clear();
                serialPort->close();
            }
            */

            serialPort->close();
            if(!serialPort->open(QIODevice::ReadWrite))
            {
                qDebug()<<info.portName()<<" 打开失败!";
                delete serialPort;
                serialPort = nullptr;
                continue;
            }

            serialPort->setBaudRate(115200);
            serialPort->setDataBits(QSerialPort::Data8);
            serialPort->setParity(QSerialPort::NoParity);
            serialPort->setStopBits(QSerialPort::OneStop);
            serialPort->setFlowControl(QSerialPort::NoFlowControl);

            QString sendHandshake="68020268CBB17C16";
            QString ResponseHandshake ="68020268ABB15C16";

            qDebug() << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss zzz]") <<
                        "Sent Handshake command:"<<info.portName()<<sendHandshake;

            serialPort->write(QByteArray::fromHex(sendHandshake.toUtf8()));

            msleep(3000);

            if(serialPort->waitForReadyRead(2000)){

                msleep(3000);
                QByteArray revBuffer= serialPort->readAll();
                QString revHandshake = revBuffer.toHex().toUpper();

                if( revHandshake == ResponseHandshake ){

                    qDebug() << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss zzz]") <<
                                "Received Handshake response: "<<revHandshake;
                    qDebug() << "MCU COM is :"<< info.portName();
                    com_name = info.portName();
                }
                else {
                    qDebug() <<"MCU COM receive error: "<<serialPort->portName() <<
                               revHandshake;
                }

            }
            else {

                qDebug() <<"MCU COM Time out:"<<serialPort->portName();

            }

            serialPort->close();
            delete serialPort;
            serialPort = nullptr;

            if(!com_name.isEmpty()){
                break;
            }

        }
    }

    return  com_name;
}




void Recognize_MCU_COM::run()
{   
    qDebug() <<"Recognize_MCU_COM THREAD : "<<QThread::currentThread();
    QString mcu_COM = Recognize_MCU_COM::FindMCU_COM();
    QString recognized_COM_Name;

    if( mcu_COM.isEmpty() ){
        qDebug() << "MCU  serial port is  EMPTY!";

        QString title ="MCU串口提示",text = "未能识别MUC串口，请重新识别！";
        QMetaObject::invokeMethod(this->parent, "UI_top_message_box"
                                  ,QGenericArgument("QString", &title)
                                  ,QGenericArgument("QString", &text));
        return;
    }



    // 设置串口号
    QSerialPort * serialPort = new QSerialPort();
    serialPort->setPortName(mcu_COM);
    if(!serialPort->open(QIODevice::ReadWrite))
    {
        delete serialPort;
        serialPort = nullptr;
        return;

    }

    serialPort->setBaudRate(115200);
    serialPort->setDataBits(QSerialPort::Data8);
    serialPort->setParity(QSerialPort::NoParity);
    serialPort->setStopBits(QSerialPort::OneStop);
    serialPort->setFlowControl(QSerialPort::NoFlowControl);


    /*
     * 识别4G模块第一个串口
     */

    QString sendOpenCOM1 ="68020268C221E316";
    QString ResponseopenCOM1 ="68020268A221C316";

    qDebug() <<"Sent Command to Open Channal No.1 :"<<sendOpenCOM1;
    serialPort->write(QByteArray::fromHex(sendOpenCOM1.toUtf8()));

    if (serialPort->waitForBytesWritten()) {

        if (serialPort->waitForReadyRead()) {

            QByteArray responseData = serialPort->readAll();
            while (serialPort->waitForReadyRead(1000))
            {
                responseData += serialPort->readAll();
            }

            QString revString=responseData.toHex().toUpper();
            qDebug() <<"Channal No.1 Received:"<<revString;

            if(revString==ResponseopenCOM1){

                msleep(12000);// 等待Windows串口准备好，时间是个经验值

                //,Qt::BlockingQueuedConnection,QGenericReturnArgument("QString",&recognize_COM_Name)
                QMetaObject::invokeMethod(this->parent, "recognize_4G_COM"
                                          ,Qt::BlockingQueuedConnection,
                                          QGenericReturnArgument("QString",&recognized_COM_Name)
                                          ,QGenericArgument("QString", &recognized_COM_Name));

                qDebug() << "recognize_COM_name:" <<recognized_COM_Name;

                /*
                // Wait End of UI update
                parent->mutex_ui_update.lock();
                if(parent->waitCon_ui_update.wait(&parent->mutex_ui_update,4000)){

                    recognized_COM_Name = parent->recognize_COM_Name;
                    qDebug() << "recognize_COM_name:" <<recognized_COM_Name;
                }
                else {
                    qDebug() << "recognize_COM_name TIMEOUT! ";
                }

                qDebug() << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss zzz]") <<"End of UI Update!";
                parent->mutex_ui_update.unlock();

                */
            }
            else {
                qDebug() <<"Channal No.1 Receive ERROR: "<<serialPort->portName();
                serialPort->clear();
            }

        }
    }

    /*
     * 识别4G模块第二个串口
     */

    if(serialPort!=nullptr){

        QString sendOpenCOM2 ="68020268C223E516";
        QString ResponseopenCOM2 ="68020268A223C516";

        qDebug() <<"Sent Command to Open Channal No.2 :"<<sendOpenCOM2;
        qint64 write_result=  serialPort->write(QByteArray::fromHex(sendOpenCOM2.toUtf8()));

        if (serialPort->waitForBytesWritten()) {

            if (serialPort->waitForReadyRead()) {

                QByteArray responseData = serialPort->readAll();
                while (serialPort->waitForReadyRead(1000))
                    responseData += serialPort->readAll();

                QString revString=responseData.toHex().toUpper();
                qDebug() <<"Channal No.2 Received:"<<revString;

                if(revString==ResponseopenCOM2){

                    msleep(12000);// 等待Windows串口准备好，时间是个经验值

                    //,Qt::BlockingQueuedConnection,QGenericReturnArgument("QString",&recognize_COM_Name)
                    QMetaObject::invokeMethod(this->parent, "recognize_4G_COM"
                                              ,Qt::BlockingQueuedConnection,
                                              QGenericReturnArgument("QString",&recognized_COM_Name)
                                              ,QGenericArgument("QString", &recognized_COM_Name));

                    qDebug() << "recognize_COM_name:" <<recognized_COM_Name;

                    /*
                    // Wait End of UI update
                    parent->mutex_ui_update.lock();
                    if(parent->waitCon_ui_update.wait(&parent->mutex_ui_update,4000)){

                        recognized_COM_Name = parent->recognize_COM_Name;
                        qDebug() << "recognize_COM_name:" <<recognized_COM_Name;
                    }
                    else {
                        qDebug() << "recognize_COM_name TIMEOUT! ";
                    }

                    qDebug() << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss zzz]") <<"End of UI Update!";
                    parent->mutex_ui_update.unlock();
                    */
                }
                else {
                    qDebug() <<"Channal No.2 Receive ERROR: "<<serialPort->portName();
                    serialPort->clear();
                }

            }
        }


   }

    if(serialPort!=nullptr){
        serialPort->close();

        delete  serialPort;
        serialPort=nullptr;
    }



}


void Recognize_MCU_COM::receive_data()
{
    // increace despise,spice of yield to thread produce




}
